package com.yboot.stater.websocket.config;

import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @author Yangcs
 * @date 2025/08/27
 */
@AutoConfiguration
@ConditionalOnProperty(value = "yboot.websocket.stomp.enable", havingValue = "true")
@EnableConfigurationProperties(value = StompProperties.class)
@EnableWebSocketMessageBroker
@AllArgsConstructor
@Import(StompToolConfiguration.class)
public class StompAutoConfiguration implements WebSocketMessageBrokerConfigurer {

    private StompProperties stompProperties;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 定义 stomp 端点
        registry.addEndpoint(stompProperties.getEndpoint())
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 将满足前缀的订阅，转发给 broker
        registry.enableSimpleBroker(stompProperties.getDestinationPrefixes());

        // 将满足前缀的订阅，会发给 @MessageMapping 注解的方法
        registry.setApplicationDestinationPrefixes(stompProperties.getApplicationDestinationPrefixes());
    }

}